package com.petsbang.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class FileTools {
	// 目录名
	private static final String dirName = Environment.getExternalStorageDirectory() + "/PetsDownload/";

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	public static void savePicFile(Bitmap bm, String fileName) throws Exception {
		fileName = fileName.substring(fileName.lastIndexOf("/"));
		File dirFile = new File(dirName);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		File myCaptureFile = new File(dirName + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
	}

	/**
	 * 读取图片
	 * 
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static Bitmap readPicFile(String fileName) throws IOException {
		fileName = fileName.substring(fileName.lastIndexOf("/"));
		String filepath = dirName + fileName;
		File file = new File(filepath);
		if (file.exists()) {
			// decode image size
//			BitmapFactory.Options o = new BitmapFactory.Options();
//			o.inJustDecodeBounds = true;
//			BitmapFactory.decodeStream(new FileInputStream(file), null, o);
//
//			// Find the correct scale value. It should be the power of 2.
//			final int REQUIRED_SIZE = 70;
//			int width_tmp = o.outWidth, height_tmp = o.outHeight;
//			int scale = 1;
//			while (true) {
//				if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
//					break;
//				width_tmp /= 2;
//				height_tmp /= 2;
//				scale *= 2;
//			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = 1;
			return BitmapFactory.decodeStream(new FileInputStream(file), null, o2);
		} else {
			return null;
		}
	}

	public static boolean isFileExist(String fileName) {
		fileName = fileName.substring(fileName.lastIndexOf("/"));
		String filepath = dirName + fileName;
		File file = new File(filepath);
		if (file.exists()) {
			return true;
		} else {
			return false;
		}
	}
}
